// Created by carolsail

// 随机整数
export function random(lower: number, upper: number): number {
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}

// 字符串中包含数字，提取数字进行排序
export function sortSpriteNameByNum(frames: cc.SpriteFrame[]) {
    const getNumberInSpriteName = (name: string) => {
        const reg = /\d+/g
        return parseInt(name.match(reg)[0] || '0')
    }
    return frames.sort((a, b) => getNumberInSpriteName(a.name) - getNumberInSpriteName(b.name))
}

// 微信头像链接
export function wxAvatar(avatarUrl: string, isCached: boolean = true) {
    if (isCached) {
        avatarUrl += `?sail.jpg`
    } else {
        const time = new Date().getTime()
        avatarUrl += `?sail=${time}.jpg`
    }
    return new Promise<void>((resolve, reject) => {
        cc.loader.load(avatarUrl, function (err: any, texture: any) {
            if (err) reject && reject()
            resolve && resolve(texture)
        })
    })
}

// 生成uuid
export function uuid() {
    let d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}